plasmoid.include("3rdparty/tinyxmldom.js") // For documentation see http://xmljs.sourceforge.net/website/documentation-classicdom.html
plasmoid.include("helper.js")
/*
 *  Init Functions
 */

function initialize() {
    // Initialize variables
    plasmoid.globals = {} // Place to store global variables
    plasmoid.globals.feed = {}
    plasmoid.globals.feed.emails = {}
    plasmoid.globals.feed.ids = []
    
    // Listen for config changes
    plasmoid.addEventListener('ConfigChanged', configChanged)
}

function configChanged() {
    
    // Pause timer
    polltimer.running = false
    
    // Read configuration
    plasmoid.globals["username"] = String(plasmoid.readConfig("username"))
    plasmoid.globals["passwd"] = String(plasmoid.readConfig("passwd"))
    plasmoid.globals["pollinterval"] = plasmoid.readConfig("pollinterval")
    
    if (plasmoid.globals.username == "") {
        // Update overlay
        overlayImage.setErrors()
        setTooltip("Error", "Account not configured.")
    } else {        
        // Update overlay
        overlayImage.setClear()
        
        // Poll account for email
        pollaccount(plasmoid.globals.username)
        
        // Initialize and start timer
        polltimer.interval = plasmoid.globals.pollinterval * 60000
        polltimer.running = true    
    }
}

/*
 *  Gmail Functions
 */

function pollaccount() {
    
    print("Polling account...")
    var feed = ""
    
    // Select the URL to use (deal with different domains)
    var atomurl = "https://mail.google.com/mail/feed/atom/"
    if (plasmoid.globals.username.indexOf("@") != -1) {
        var domain = plasmoid.globals.username.substring(plasmoid.globals.username.indexOf("@")+1, plasmoid.globals.username.length)
        if (domain != "gmail.com" && domain != "googlemail.com" && domain.length != 0) {
            atomurl = "https://mail.google.com/a/"+domain+"/feed/atom/"
        }    
    }
    var u = new Url(atomurl)
    u.user = plasmoid.globals.username
    u.passwd = plasmoid.globals.passwd
    
    var getJob = plasmoid.getUrl(u)
    
    function recv(job, data)
    {
        if (job == getJob) {
            if (data.length) {
                feed += decodeURIComponent(escape(data.valueOf()))
            }
        }
    }

    function finished(job)
    {
        if (job == getJob) {
            print("Done getting atom data.")
            parsefeed(feed)
        }
    }

    getJob.data.connect(recv)
    getJob.finished.connect(finished)    
}


function parsefeed(feed) {
    
    // Check for an empty feed
    if (feed == "") {
        overlayImage.setErrors()
        setTooltip("Error", "Error fetching list of emails.")
    } else {
        overlayImage.setClear()
        
        // Start XML parser
        var objDom = new XMLDoc(feed, xmlError)
        var objDomTree = objDom.docNode
        
        // feed structure
        var f = {}
        
        // Get header information
        f.fullcount = objDomTree.getElements("fullcount")[0].getText()
        f.link = objDomTree.getElements("link")[0].getAttribute("href")
        
        // Get all of the emails listed
        f.emails = []
        f.newemails = []
        f.ids = []
        var entryElements = objDomTree.getElements("entry")
        
        for (var e in entryElements)
        {
            var entry = entryElements[e].getElements()
            
            f.emails[e] = {}
            for (var i in entry)
            {
                switch(entry[i].tagName) {
                    case "title":
                        f.emails[e]["subject"] = entry[i].getText()
                        break;
                    case "author":
                        f.emails[e]["authorname"] = entry[i].getElements("name")[0].getText()
                        f.emails[e]["authoremail"] = entry[i].getElements("email")[0].getText()
                        break;
                    case "id":
                        f.emails[e]["id"] = entry[i].getText()
                        f.ids.push(entry[i].getText())
                        break;
                }
            }
        }
        
        // Find new emails
        for (var i in f.emails) {
            if (plasmoid.globals.feed.ids.indexOf(f.emails[i]["id"]) == -1) {
                f.newemails.push(f.emails[i])
            }
        }
        
        // Set the global list of emails
        plasmoid.globals.feed = f

        // Update the display
        updateDisplay(f)    
    }
}

function xmlError(e) {
    print(e);
}

/*
 *  Display Functions
 */

function updateDisplay(f) {

    // Display the number of unread emails
    count.text = f.fullcount
        
    // Set the plasmoid to inactive if there are no unread emails
    if (f.emails.length == 0) {
        // No unread emails
        plasmoid.status = PassiveStatus
        count.text = ""
        envelopeImage.source = "plasmapackage:/images/gmail-plasmoid-gray.svg"
        setTooltip("", "")
    } else {
        plasmoid.status = ActiveStatus
        envelopeImage.source = "plasmapackage:/images/gmail-plasmoid.svg"
        
        // Display the number of unread emails
        count.text = f.fullcount
        
        // Update the toolTip
        var t = ""
        for (var i in f.emails) {
            t += '<tr><td><p style="margin-left: 50px ; text-indent: -50px;">['+f.emails[i].authorname+'] '+f.emails[i].subject+'</p></td></tr>'
        }
        setTooltip("Threads", "<table>"+t+"</table>")
        
        // Send new message notification (if applicable)
        if (f.newemails.length > 0) {
            t = ""
            if (f.newemails.length == 1) {
                // We have 1 new email
                t = "<table><tr><td><b>"+i18n("From")+"</b>: </td><td>"+f.newemails[0].authorname+"</td></tr><tr><td><b>"+i18n("Subject")+"</b>: </td><td>"+f.newemails[0].subject+"</td></tr></table>"
            } else {
                // We have more than 1 new email
                t = i18np("You have <b>%1</b> new message.", "You have <b>%1</b> new messages.", f.newemails.length)
            }
            
            // Send Notification
            sendNotification("Emails", t)
        }
    }
}

function setTooltip(mainText, subText) {
    toolTip.mainText = mainText
    toolTip.subText = subText
}

function sendNotification(summary, body) {
    // Notification
    print("Sending notification.")
    engine = dataEngine("notifications")
    service = engine.serviceForSource("notification")
    op = service.operationDescription("createNotification")
    op["appName"] = "gmail-plasmoid"
    op["appIcon"] = plasmoid.file("images", "gmail-plasmoid.svg")
    op["summary"] = summary
    op["body"] = body
    op["timeout"] = 3000
    service.startOperationCall(op)
}

